package me.helllp.dake.generator.meta;

import lombok.Getter;
import lombok.Setter;
import me.helllp.dake.common.anno.MataGenerator;
import me.helllp.dake.generator.config.ServiceConfiguration;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务的元数据信息：对应ServiceConfiguration
 */
@Getter
public class ServiceMetaData extends AbstractMetaData {
    private ServiceConfiguration serviceConfiguration;

    /**
     * 服务名
     */
    private String serviceName;

    /**
     * 服务默认的端口
     */
    private String port;

    @MataGenerator
    private Map<String, Object> configMap;

    public ServiceMetaData(ServiceConfiguration serviceConfiguration) throws InvocationTargetException, IllegalAccessException, IOException {
        this.serviceConfiguration = serviceConfiguration;
        // 属性拷贝
        BeanUtils.copyProperties(this, serviceConfiguration);
        // 初始化属性设置
        initMetaData();
    }

    @Override
    public void initMetaData() throws IOException, InvocationTargetException, IllegalAccessException {
        this.configMap = builder();
    }

    /**
     * 处理服务配置信息
     *
     * @return
     */
    private Map<String, Object> builder() {
        Map<String, Object> map = new HashMap<>();
        // 必须设置，并且不能使用下划线，用中划线替代
        map.put(ProjectPropertyRegistry.SPRING_MVC_PATHMATCH, "ant_path_matcher");
        map.put(ProjectPropertyRegistry.SPRING_APPLICATION_NAME, serviceConfiguration.getServiceName());

        if (!StringUtils.isEmpty(serviceConfiguration.getPort())) {
            map.put(ProjectPropertyRegistry.SERVER_PORT, serviceConfiguration.getPort());
        }

        if (!ObjectUtils.isEmpty(serviceConfiguration.getDiscoveryServerConfig())) {
            map.put(ProjectPropertyRegistry.SPRING_CLOUD_DISCOVERY, serviceConfiguration.getDiscoveryServerConfig().getServerAddress());
            map.put(ProjectPropertyRegistry.SPRING_CLOUD_DISCOVERY_ENABLED, "true");
        }

        if (!ObjectUtils.isEmpty(serviceConfiguration.getConfigServerConfig())) {
            map.put(ProjectPropertyRegistry.SPRING_CLOUD_CONFIG, serviceConfiguration.getConfigServerConfig().getServerAddress());
            map.put(ProjectPropertyRegistry.SPRING_CLOUD_CONFIG_ENABLED, "true");
            map.put(ProjectPropertyRegistry.SPRING_CLOUD_CONFIG_FILE_EXTENSION, "yaml");
        }

        return map;
    }

}
